package com.code.petapp.util

import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowInsets
import androidx.annotation.RequiresApi

object KeyboardUtils {
    interface KeyboardVisibilityListener {
        fun onKeyboardVisibilityChanged(isVisible: Boolean, keyboardHeight: Int)
    }

    private fun setKeyboardVisibilityListener(activity: Activity, listener: KeyboardVisibilityListener) {
        val contentView = activity.findViewById<View>(android.R.id.content)
        contentView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            private var previousKeyboardState = false
            private var keyboardHeight = 0
            override fun onGlobalLayout() {
                val rect = Rect()
                contentView.getWindowVisibleDisplayFrame(rect)
                val screenHeight = contentView.rootView.height
                val keypadHeight = screenHeight - rect.bottom
                val isKeyboardVisible = keypadHeight > screenHeight * 0.15
                if (isKeyboardVisible) {
                    keyboardHeight = keypadHeight
                }

                if (isKeyboardVisible != previousKeyboardState) {
                    previousKeyboardState = isKeyboardVisible
                    listener.onKeyboardVisibilityChanged(isKeyboardVisible, keyboardHeight)
                }
            }
        })
    }

    @RequiresApi(Build.VERSION_CODES.R)
    private fun setKeyboardVisibilityListenerApi30(activity: Activity, listener: KeyboardVisibilityListener) {
        val rootView = activity.window.decorView
        rootView.setOnApplyWindowInsetsListener { _, insets ->
            val isKeyboardVisible = insets.isVisible(WindowInsets.Type.ime())
            val keyboardHeight = if (isKeyboardVisible) {
                insets.getInsets(WindowInsets.Type.ime()).bottom
            } else {
                0
            }
            listener.onKeyboardVisibilityChanged(isKeyboardVisible, keyboardHeight)
            insets
        }
    }

    fun setKeyboardVisibilityListenerAuto(activity: Activity, listener: KeyboardVisibilityListener) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            setKeyboardVisibilityListenerApi30(activity, listener)
        } else {
            setKeyboardVisibilityListener(activity, listener)
        }
    }
}